# 维修价格服务
from models import db, RepairPrice
from common.response import APIResponse

class RepairPriceService:
    @staticmethod
    def get_price_by_id(price_id):
        price = RepairPrice.query.filter_by(id=price_id).first()
        if not price:
            return APIResponse.not_found('Repair price not found')
        return APIResponse.success(price.to_dict())

    @staticmethod
    def get_all_prices(args):
        # 分页查询
        page = args.get('page', 1, type=int)
        per_page = args.get('pageSize', 10, type=int)
        item_name = args.get('item_name')
        if item_name:
            prices = RepairPrice.query.filter(RepairPrice.item_name.like(f'%{item_name}%')).paginate(page=page, per_page=per_page, error_out=False)
        else:
            prices = RepairPrice.query.paginate(page=page, per_page=per_page, error_out=False)
        return APIResponse.success({
            'total': prices.total,
            'items': [price.to_dict() for price in prices.items]
        })

    @staticmethod
    def get_price_by_item_name(item_name):
        prices = RepairPrice.query.filter_by(item_name=item_name).all()
        return APIResponse.success([price.to_dict() for price in prices])

    @staticmethod
    def create_price(data):
        # 验证必填字段
        required_fields = ['item_name', 'price']
        for field in required_fields:
            if field not in data or not data[field]:
                return APIResponse.validate_error(f'{field} is required')

        # 验证价格格式
        try:
            price_value = float(data['price'])
            if price_value < 0:
                return APIResponse.validate_error('Price cannot be negative')
        except (ValueError, TypeError):
            return APIResponse.validate_error('Price must be a valid number')

        # 检查是否已存在同名项目
        existing = RepairPrice.query.filter_by(item_name=data['item_name']).first()
        if existing:
            return APIResponse.fail('Item with this name already exists', 10002)

        # 创建新价格记录
        new_price = RepairPrice(
            item_name=data['item_name'],
            price=price_value,
            description=data.get('description')
        )

        try:
            new_price.save()
            return APIResponse.success(new_price.to_dict(), 'Repair price created successfully')
        except Exception as e:
            db.session.rollback()
            return APIResponse.fail(f'Database error: {str(e)}', 10003)

    @staticmethod
    def update_price(price_id, data):
        price = RepairPrice.query.filter_by(id=price_id).first()
        if not price:
            return APIResponse.not_found('Repair price not found')

        # 检查更新的项目名称是否已存在
        if 'item_name' in data and data['item_name'] != price.item_name:
            existing = RepairPrice.query.filter_by(item_name=data['item_name']).first()
            if existing:
                return APIResponse.fail('Item with this name already exists', 10002)
            price.item_name = data['item_name']

        # 更新价格
        if 'price' in data:
            try:
                price_value = float(data['price'])
                if price_value < 0:
                    return APIResponse.validate_error('Price cannot be negative')
                price.price = price_value
            except (ValueError, TypeError):
                return APIResponse.validate_error('Price must be a valid number')

        # 更新描述
        if 'description' in data:
            price.description = data['description']

        try:
            price.save()
            return APIResponse.success(price.to_dict(), 'Repair price updated successfully')
        except Exception as e:
            db.session.rollback()
            return APIResponse.fail(f'Database error: {str(e)}', 10003)

    @staticmethod
    def delete_price(price_id):
        price = RepairPrice.query.filter_by(id=price_id).first()
        if not price:
            return APIResponse.not_found('Repair price not found')

        try:
            db.session.delete(price)
            db.session.commit()
            return APIResponse.success({}, 'Repair price deleted successfully')
        except Exception as e:
            db.session.rollback()
            return APIResponse.fail(f'Database error: {str(e)}', 10003)